import logging
from fastapi import APIRouter, Query
from tortoise.expressions import Q

from app.controllers import idiom_controller
from app.schemas.base import Success, SuccessExtra, Fail
from app.schemas.idiom import IdiomUpdate, IdiomCreate
from typing import List

logger = logging.getLogger(__name__)
router = APIRouter()


@router.get("/list", summary="成语列表")
async def list_idiom(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        word: str = Query("", description="名称，用于查询"),
        # categoryCode: str = Query("", description="类别编码")
):
    q = Q()
    if word:
        word = Q(word__contains=word)
    # if categoryCode:
    #     q = Q(categoryCode__contains=categoryCode)
    total, idiom_objs = await idiom_controller.list(page=page, page_size=page_size, search=q)
    data = [await obj.to_dict() for obj in idiom_objs]
    return SuccessExtra(data=data, message='success', total=total, page=page, page_size=page_size)


@router.post("/create", summary="创建成语")
async def create_idiom(idiom_in: IdiomCreate):
    await idiom_controller.create(obj_in=idiom_in)
    return Success(message="添加成功")


@router.post("/create_bulk", summary="批量创建成语")
async def create_idiom_bulk(idiom_list: List[IdiomCreate]):
    await idiom_controller.create_bulk(obj_list=idiom_list)
    return Success(message="批量添加成功")


@router.post("/update", summary="更新成语")
async def update_idiom(idiom_in: IdiomUpdate):
    # 更新当前类别
    await idiom_controller.update(id=idiom_in.id, obj_in=idiom_in)
    return Success(message="修改成功")


@router.delete("/delete", summary="删除成语")
async def delete_idiom(idiom_id: int = Query(..., description="类别ID")):
    await idiom_controller.remove(id=idiom_id)
    return Success(message="删除成功")
